package com.quanfaqiang.demo1.intercepters;



import com.quanfaqiang.demo1.utils.JwtUtil;
import com.quanfaqiang.demo1.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;

@Component
public class Logininterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());


        //令牌验证
        String token = request.getHeader("smarthome");
        System.out.println(token);
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get("token");
            System.out.println(redisToken+"=================");
            if (redisToken==null){
                throw new RuntimeException();
            }
            if (!redisToken.equals(token)){
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);//把业务数据储存为ThreaddLocal中
            System.out.println(claims+"+++++++++++++++++++++++");
            return true;

        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
